package com.ray.generator.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ray.generator.common.BaseController;
import com.ray.generator.entity.TableEntity;
import com.ray.generator.service.GeneratorService;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Ray
 * @date 2018/12/19
 * 代码生成器
 */
@Controller
@RequestMapping("/system/sysGenerator")
public class GeneratorController extends BaseController {

    private String prefix = "system/sysGenerator";

    @Autowired
    private GeneratorService generatorService;

    /**
     * 视图
     */
    @GetMapping()
    public String sysGenerator() {
        return prefix + "/sysGenerator";
    }

    /**
     * 列表
     */
    @ResponseBody
    @GetMapping("/list")
    public JSONObject list(int page, int limit,
                           @RequestParam(value = "keyword", required = false) String tableName) {

        Page<TableEntity> pages = new Page<>(page, limit);
        IPage<TableEntity> tableEntityIPage = generatorService.myQueryList(pages, tableName);

        return jsonObject(tableEntityIPage);
    }

    /**
     * 生成代码
     */
    @GetMapping("/code")
    public void code(String tables, HttpServletResponse response) throws IOException {
        byte[] data = generatorService.generatorCode(tables.split(","));

        response.reset();
        response.setHeader("Content-Disposition", "attachment; filename=" + tables.toLowerCase() + ".zip");
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream; charset=UTF-8");

        IOUtils.write(data, response.getOutputStream());

    }
}
